import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:bai_le_men_im/pages/redEnvelopeDetail.dart';
import 'package:flutter/material.dart';
import '../constants.dart' show Constants;
import 'dart:async';
import 'package:photo_view/photo_view.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';

class ConversationItemContent extends StatefulWidget {
  final content;
  final Color color;
  final bool reverse;
  final double uploadProgress;
  final FlutterSound flutterSound;
  final int messageId;
  final String status;
  final dynamic payload;
  ConversationItemContent(
      {@required this.content,
      this.color = Colors.white,
      this.uploadProgress = 1.0,
      @required this.flutterSound,
      @required this.messageId,
      @required this.payload,
      this.status,
      this.reverse = false});
  @override
  _ConversationItemContentState createState() =>
      _ConversationItemContentState();
}

class _ConversationItemContentState extends State<ConversationItemContent> {
  bool hasListenSendStatus = false;
  double uploadProgress = 1.0;

  sendMessageOnMediaUpload(dynamic event) async {
    if (hasListenSendStatus) {
      hasListenSendStatus = false;
      FlutterWildfire.off("sendMessageOnProgress", sendMessageOnProgress);
      FlutterWildfire.off("sendMessageOnMediaUpload", sendMessageOnMediaUpload);
    }
  }

  sendMessageOnProgress(dynamic event) async {
    dynamic message = event['message'];
    if (message['messageId'] == widget.messageId) {
      this.setState((){
        uploadProgress = event['uploaded'] / event['total'];
      });
    }
  }
  
  @override
  void initState() {
    super.initState();
    if (widget.reverse && widget.payload['status'] == 'Sending') {
      hasListenSendStatus = true;
      FlutterWildfire.on("sendMessageOnProgress", sendMessageOnProgress);
      FlutterWildfire.on("sendMessageOnMediaUpload", sendMessageOnMediaUpload);
    }
  }

  @override
  void dispose() {
    if (hasListenSendStatus) {
      FlutterWildfire.off("sendMessageOnProgress", sendMessageOnProgress);
      FlutterWildfire.off("sendMessageOnMediaUpload", sendMessageOnMediaUpload);
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final content = widget.content;
    final Color color = widget.color;
    final bool reverse = widget.reverse;
    final FlutterSound flutterSound = widget.flutterSound;
    /* 图片类型
    content: {
      content: {
        thumbnailBytes : list[],
        localPath : '',
        mediaType: "IMAGE",
        remoteUrl: '',
        extra: '',
        mentionedType: 0
      }
    }
    */

    /*语音类型
    content: {
      duration: 1, 
      localPath: , 
      mediaType: VOICE, 
      remoteUrl: http://47.90.126.14:80/fs/2/2019/09/18/11/247e99e1787f49bb9f01515da122cca0, 
      extra: , 
      mentionedType: 0
    }
    */

    /* 文字类型
    content: {
        content: '文字内容',
        extra: '',
        mentionedTargets: []
        mentionedType: 0
    }
    */
    if (content['content'] is String) {
      return Flexible(
        child: Container(
          // height: 100.0,

          margin: EdgeInsets.symmetric(
            horizontal: 15.0,
          ),
          padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 13.0),
          decoration: BoxDecoration(
              color: color, borderRadius: BorderRadius.circular(3.0)),
          child: Text(
            content['content'],
            style: TextStyle(fontSize: 17.0),
          ),
        ),
      );
    }
    if (content['type'] != null && content['type'] == 1001) {
      // 红包
      return Expanded(
        child: Container(
            margin: EdgeInsets.symmetric(
              horizontal: 15.0,
            ),
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(3.0)),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(Constants.AvatarRadius),
              child: InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) => new RedEnvelopeDetail(
                              detail: content['content'])),
                    );
                  },
                  child: Container(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Container(
                          color: Colors.yellow[900],
                          padding: EdgeInsets.all(10.0),
                          child: Row(
                            children: <Widget>[
                              SizedBox(
                                width: 2.0,
                              ),
                              Image.asset(
                                'assets/images/ad_game_notify.png',
                                width: 35.0,
                              ),
                              SizedBox(
                                width: 12.0,
                              ),
                              Text(
                                '恭喜发财，大吉大利',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 16.0),
                              )
                            ],
                          ),
                        ),
                        Container(
                          color: Colors.white,
                          child: Padding(
                            padding: EdgeInsets.all(10.0),
                            child: Text(
                              '积分红包',
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 12.0),
                            ),
                          ),
                        )
                      ],
                    ),
                  )),
            )),
      );
    }
    if (content['mediaType'] != null) {
      if (content['mediaType'] == 'IMAGE') {
        Widget img;
        if (content['thumbnailBytes'] != null) {
          img = Image.memory(
            Uint8List.fromList(
              List.generate(content['thumbnailBytes'].length, (int index) {
                return content['thumbnailBytes'][index];
              }),
            ),
          );
        } else {
          if (content['localPath'] != null &&
              content['localPath'].toString().isNotEmpty) {
            File imgFile = File(content['localPath']);
            img = Image.file(
              imgFile,
              width: double.parse(content['thumbnail']['mWidth'].toString()),
              height: double.parse(content['thumbnail']['mHeight'].toString()),
              fit: BoxFit.cover,
            );
          } else {
            print('未处理的图片');
            print(content);
            img = Container();
          }
        }
        if (this.uploadProgress < 1.0) {
          img = Stack(
            children: <Widget>[
              img,
              Positioned(
                top: 0.0,
                right: 0.0,
                bottom: 0.0,
                left: 0.0,
                child: Container(
                  color: Colors.black
                      .withAlpha(((0.5 - this.uploadProgress * 0.5) * 255).toInt() ),
                  child: Center(
                    child: SizedBox(
                      width: 20.0,
                      height: 20.0,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.0,
                        value: uploadProgress,
                        // TODO: 进度条
                      ),
                    ),
                  ),
                ),
              )
            ],
          );
        }

        return Container(
            margin: EdgeInsets.symmetric(
              horizontal: 15.0,
            ),
            decoration: BoxDecoration(
                color: Colors.grey[200], borderRadius: BorderRadius.circular(3.0)),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(Constants.AvatarRadius),
              child: InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) => Scaffold(
                                body: PhotoView(
                                    imageProvider:
                                        NetworkImage(content['remoteUrl'])),
                              )),
                    );
                  },
                  child: img),
            ));
      } else if (content['mediaType'] == 'FILE') {
        // TODO: 表情
        return Container(
            margin: EdgeInsets.symmetric(
              horizontal: 15.0,
            ),
            decoration: BoxDecoration(
                color: color, borderRadius: BorderRadius.circular(3.0)),
            child: Container(
              color: Colors.redAccent,
              padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 13.0),
              child: Text('暂不支持的媒体类型'),
            ));
      } else if (content['mediaType'] == 'VOICE') {
        // TODO: 语音
        List<Widget> widgets;
        Widget rowWidget;
        if (reverse) {
          widgets = <Widget>[
            Transform.rotate(
              angle: reverse ? (pi / 180.0 * -90) : (pi / 180.0 * 90),
              child: Icon(
                Icons.wifi,
                size: 15.0,
              ),
            ),
            SizedBox(
              width: 5.0,
            ),
            Text(content['duration'].toString() + '"')
          ];
          rowWidget = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: widgets,
          );
        } else {
          widgets = <Widget>[
            Text(content['duration'].toString() + '"'),
            SizedBox(
              width: 5.0,
            ),
            Transform.rotate(
              angle: reverse ? (pi / 180.0 * -90) : (pi / 180.0 * 90),
              child: Icon(
                Icons.wifi,
                size: 15.0,
              ),
            ),
          ];
          rowWidget = Row(
            children: widgets,
          );
        }
        return Flexible(
          child: InkWell(
            onTap: () async {
              flutterSound.stopPlayer();
              Future<String> result =
                  flutterSound.startPlayer(content['remoteUrl']);
              // String path = await result();
            },
            child: Container(
              // height: 100.0,
              width: 60 + content['duration'] * 4.0,
              margin: EdgeInsets.symmetric(
                horizontal: 15.0,
              ),
              padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 13.0),
              decoration: BoxDecoration(
                  color: color, borderRadius: BorderRadius.circular(3.0)),
              child: rowWidget,
            ),
          ),
        );
      }

      print('未知的媒体类型');
      print(content);
      return Container(
        color: Colors.red,
        height: 20.0,
      );
    }
    print('未知的类型');
    print(content['content']);
    return Container(
      color: Colors.red,
      height: 20.0,
    );
  }
}

class SendStatus extends StatelessWidget {
  final String status;
  SendStatus(this.status);
  @override
  Widget build(BuildContext context) {
    switch (status) {
      case 'Sent':
      // case 'Sending':
        return Container();
        break;
      case 'Sending':
        return Container(
          height: 45.0,
          child: const Center(
            child: SizedBox(
              width: 10.0,
              height: 10.0,
              child: CircularProgressIndicator(
                strokeWidth: 1.0,
              ),
            ),
          ),
        );
        break;
      case 'Send_Failure':
        return Container(
          height: 45.0,
          child: Icon(
            Icons.error,
            color: Colors.redAccent[100],
          ),
        );
        break;
      default:
        print('未处理消息的状态');
        print(status);
        // TODO: 未处理的状态
        /*
    Mentioned(3),
    AllMentioned(4),
    Unread(5),
    Readed(6),
    Played(7);
    */
        return Container();
    }
  }
}
